from django.contrib import admin
from django.contrib.auth.admin import UserAdmin
from django.forms import BaseInlineFormSet
from django.utils.safestring import mark_safe
from jet.admin import CompactInline
from jet.filters import DateRangeFilter

from .models import *

admin.site.register(User, UserAdmin)

# Register your models here.

# list_editable = ['machine_room_id', 'temperature']
# TabularInline 横向
# StackedInline 纵向

admin.site.site_header = 'HotManga后台管理'
admin.site.site_title = 'HotManga后台管理'


class DeleteBaseAdmin(admin.ModelAdmin):
    actions = ['delete_bulk']

    def get_actions(self, request):
        actions = super(DeleteBaseAdmin, self).get_actions(request)
        del actions['delete_selected']
        return actions

    def delete_bulk(self, request, obj):
        for o in obj.all():
            o.delete()

    delete_bulk.short_description = '批量删除选中内容'

    def get_queryset(self, request):
        qs = super().get_queryset(request)
        return qs.filter(b_deleted=False)

    def save_model(self, request, obj, form, change):
        obj.modifier = request.user
        super().save_model(request, obj, form, change)


class DeleteComicAdmin(admin.ModelAdmin):
    actions = ['delete_bulk']

    def get_actions(self, request):
        actions = super(DeleteComicAdmin, self).get_actions(request)
        del actions['delete_selected']
        return actions

    def delete_bulk(self, request, obj):
        for o in obj.all():
            o.delete()

    delete_bulk.short_description = '批量删除选中内容'

    def save_model(self, request, obj, form, change):
        obj.modifier = request.user
        super().save_model(request, obj, form, change)


@admin.register(Recommend)
class RecommendAdmin(DeleteBaseAdmin):
    list_display = (
        "title",
        "pos",
        "type",
        "weight",
        "datetime_started",
        "datetime_ended",
    )

    list_filter = (
        "pos",
        "type",
        "pos",
        ('datetime_started', DateRangeFilter),
        ('datetime_ended', DateRangeFilter),
    )

    search_fields = (
        "title",
    )

    ordering = (
        "-datetime_created",
    )

    exclude = (
        "uuid",
        "modifier",
    )

    change_form_template = 'admin/rec_change.html'


@admin.register(Theme)
class ThemeAdmin(DeleteBaseAdmin):
    def logo_str(self, obj):
        return mark_safe(
            '<img style="width:50;height:50" src="//c.hotmangas.com/%s!backend_theme_logo"/>' % obj.logo
        )

    logo_str.short_description = "logo"

    list_display = (
        "logo_str",
        "name",
        "path_word",
        "sort",
        "color_h5",
        "lang",
        "b_deleted",
    )

    exclude = (
        "uuid",
        "modifier",
    )

    list_filter = (
        "lang",
    )

    search_fields = (
        "name",
    )

    ordering = (
        "initials",
        "-sort"
    )

    change_form_template = 'admin/theme_change.html'

    def save_model(self, request, obj, form, change):
        super().save_model(request, obj, form, change)
        # callback_theme_save_auto()


@admin.register(Tag)
class TagAdmin(DeleteBaseAdmin):
    def logo_str(self, obj):
        return mark_safe(
            '<img style="width:50;height:50" src="//c.hotmangas.com/%s!backend_theme_logo"/>' % obj.logo
        )

    logo_str.short_description = "logo"

    list_display = (
        "logo_str",
        "name",
        "gender",
        "path_word",
        "sort",
        "color_h5",
        "lang",
        "b_deleted",
    )

    exclude = (
        "uuid",
        "modifier",
    )

    list_filter = (
        "gender",
        "lang",
    )

    search_fields = (
        "name",
    )

    ordering = (
        "gender",
        "initials",
        "-sort"
    )

    change_form_template = 'admin/tag_change.html'

    def save_model(self, request, obj, form, change):
        super().save_model(request, obj, form, change)
        # callback_tag_save_auto()


@admin.register(Goods)
class GoodsAdmin(DeleteBaseAdmin):
    list_display = (
        "name",
        "uuid",
    )

    exclude = (
        "uuid",
        "modifier",
    )

    search_fields = (
        "name",
    )


@admin.register(UserInfo)
class UserInfoAdmin(DeleteBaseAdmin):
    list_display = (
        "nickname",
        "gender",
        "vip_level",
        "vip_start",
        "vip_end",
    )

    exclude = (
        "uuid",
        "modifier",
    )

    search_fields = (
        "name",
    )


@admin.register(OrderRecord)
class OrderRecordAdmin(DeleteBaseAdmin):
    list_display = (
        "user",
        "goods",
        "title",
        "no",
        "status",
        "platform",
        "price_pay",
        "price_bill",
        "datetime_vip_start",
        "datetime_vip_end",
    )

    exclude = (
        "uuid",
        "modifier",
    )

    search_fields = (
        "name",
    )


class ChapterContentInline(CompactInline):
    model = ChapterContent
    extra = 1
    show_change_link = True

    formset = BaseInlineFormSet

    exclude = (
        "modifier",
    )

    def get_queryset(self, request):
        qs = super().get_queryset(request)
        return qs.filter(b_deleted=False)


class ChapterInline(CompactInline):
    model = Chapter
    extra = 0
    fk_name = 'comic'
    can_delete = False

    formset = BaseInlineFormSet

    exclude = (
        "modifier",
    )

    def get_queryset(self, request):
        qs = super().get_queryset(request)
        return qs.filter(b_deleted=False)


# class ComicCountInline(TabularInline):
#     model = ComicCount
#     extra = 1
#     can_delete = False
#
#     formset = ComicCountFormSet
#
#     fk_name = 'comic'
#     verbose_name_plural = '漫画人气'
#     fields = (
#         "popular",
#     )


# class ComicDetailInline(TabularInline):
#     model = ComicDetail
#     extra = 1
#     can_delete = False
#     fk_name = 'comic'
#     verbose_name_plural = '漫画详情'
#     fields = (
#         "intro",
#     )


@admin.register(Comic)
class ComicAdmin(DeleteComicAdmin):
    inlines = (
        # ComicDetailInline,
        # ComicCountInline,
        ChapterInline,
    )

    def name_str(self, obj):
        red_str = '<span style="color:red">%s</span>'
        return mark_safe(
            '%s%s%s' % (
                obj.name,
                red_str % '-404' if obj.b_404 else "",
                red_str % '-隐藏' if obj.b_hidden else "",
            )
        )

    def author_str(self, obj):
        authors = list(obj.author.values_list('name', flat=True))
        names = ",".join(authors)
        return names if names.__len__() <= 10 else names[:10] + "..."

    def theme_str(self, obj):
        themes = list(obj.theme.values_list('name', flat=True))
        names = ",".join(themes)
        return names if names.__len__() <= 10 else names[:10] + "..."

    def last_chapter_name(self, obj):
        chapter = obj.last_chapter
        if not chapter:
            return "<>"
        else:
            names = chapter.name if chapter.name else '<>'
            return names if names.__len__() <= 10 else names[:10] + "..."

    # def popular(self, obj):
    #     return format_popular(obj.popular)

    name_str.short_description = "名称"
    author_str.short_description = "作者"
    theme_str.short_description = "题材"
    last_chapter_name.short_description = "最后一话"
    # popular.short_description = "人气"

    list_display = (
        "name_str",
        "author_str",
        "theme_str",
        "level",
        'restrict',
        "co",
        "status",
        # "popular",
        "datetime_updated",
        "last_chapter_name",
        "b_deleted",
    )

    exclude = (
        "uuid",
        "modifier",
        "last_chapter",
        "datetime_updated",
    )

    list_filter = (
        "level",
        "status",
        'restrict',
        'theme',
        ('datetime_updated', DateRangeFilter),
    )

    search_fields = (
        "name",
        "alias",
        "orig_name",
        "author__name",
        "chapter_comic__local__name"
    )

    ordering = (
        "-datetime_created",
    )

    filter_horizontal = [
        'author',
        'theme',
    ]

    change_form_template = 'admin/comic_change.html'

    def changeform_view(self, request, object_id=None, form_url='', extra_context=None):
        if object_id is not None:
            self.inlines = (
                # ComicDetailInline,
                # ComicCountInline,
                ChapterInline,
            )
        else:
            self.inlines = (
                # ComicDetailInline,
            )
        return super().changeform_view(request, object_id, form_url, extra_context)

    def save_model(self, request, obj, form, change):
        # if 'status' in form.changed_data:
        #     if obj.status == EnumComicStatus.Finished.value:
        #         # 查询5章以内的是短篇
        #         count = Chapter.objects.filter(comic_id=obj.uuid, b_deleted=False).count()
        #         if count < COMIC_STATUS_2_NUM:
        #             obj.status = EnumComicStatus.Short.value
        obj.modifier = request.user
        super().save_model(request, obj, form, change)
        # callback_comic_save_auto(obj.uuid)

    def delete_model(self, request, obj):
        super().delete_model(request, obj)
        # callback_comic_save_auto(obj.uuid)


@admin.register(Chapter)
class ChapterAdmin(DeleteBaseAdmin):
    inlines = (
        ChapterContentInline,
    )

    def comic_name(self, obj):
        return obj.comic.name

    comic_name.short_description = "漫画名称"

    list_display = (
        "name",
        "comic_name",
        "sort",
        "ordered",
        "group",
        "lang",
        "source",
        "type",
        "b_display",
        "count",
        "datetime_created"
    )

    list_editable = (
        "sort",
        "ordered",
        "lang",
        "source",
        "type",
    )

    exclude = (
        "sort",
        "uuid",
        "modifier",
    )

    list_filter = (
        "lang",
        "source",
        "type",
        "b_display",
        "local",
    )

    search_fields = (
        "comic__name",
        "local__name"
    )

    def changeform_view(self, request, object_id=None, form_url='', extra_context=None):
        if object_id is not None:
            self.readonly_fields = (
                "comic",
            )
        else:
            self.readonly_fields = (
            )
        return super().changeform_view(request, object_id, form_url, extra_context)


@admin.register(ChapterGroup)
class ChapterGroupAdmin(DeleteBaseAdmin):
    list_display = (
        "name",
        "lang",
    )

    exclude = (
        "uuid",
        "modifier",
    )

    list_filter = (
        "lang",
    )

    search_fields = (
        "name",
    )

    ordering = (
        "sort",
        "-datetime_created"
    )


@admin.register(Author)
class AuthorAdmin(DeleteBaseAdmin):
    list_display = (
        "name",
        "alias",
        "path_word"
    )

    exclude = (
        "uuid",
        "modifier",
    )

    search_fields = (
        "name",
        "alias",
        "path_word"
    )


@admin.register(LocalGroup)
class LocalGroupAdmin(DeleteBaseAdmin):
    list_display = (
        "name",
        "uuid",
        "alias",
        "leader",
    )

    exclude = (
        "uuid",
        "modifier",
    )

    search_fields = (
        "name",
        "alias",
        "leader",
    )

    ordering = (
        "-datetime_created",
    )
